﻿using System;
using MemoryPack;

namespace Hsenl {
    public partial class Entity {
        [OnEventSystemInitialized]
        private static void RegisterEvents() {
            PublicEvents.OnComponentAddedEvent += (entity, component) => {
                if (component is IBodied bodied) {
                    if (entity._bodied != null)
                        throw new Exception($"A entity can has only one Bodied! Component:'{component.GetType()}' Entity:'{entity.Name}'");

                    entity._bodied = bodied;
                }
            };

            PublicEvents.OnComponentRemovedEvent += (entity, component) => {
                if (component is IBodied bodied)
                    if (bodied == entity._bodied)
                        entity._bodied = null;
            };

            PublicEvents.OnEntityInstantiateEvent += entity => {
                var bodied = entity.GetComponent<IBodied>(polymorphic: true);
                if (bodied != null)
                    entity._bodied = bodied;
            };
        }

        [MemoryPackIgnore]
        private IBodied _bodied;

        [MemoryPackIgnore]
        public IBodied Bodied => this._bodied;
    }
}